<!--
 * @name crossCountryScore
 * @description 组件描述
 * @author idouya
 * @email elegentfrog@163.com
 * @date 2025-07-04
 -->

<template>
  <div class="p-cross-country-score common-bg common-layout">
    <page-title
      :discipline="gameInfo.discipline"
      :event="gameInfo.event"
      :match="gameInfo.match"
      :type="gameInfo.type"
      :startTime="gameInfo.startTime"
      :eventName="gameInfo.eventName"
    ></page-title>
    <div class="content">
      <div class="title">
        <div class="order">序号</div>
        <div class="content-detail">
          <div class="status">状态</div>
          <div class="name">姓名</div>
          <div class="horseName">单位/马名</div>
          <div class="time">进行时间</div>
          <div class="penalty">罚分</div>
        </div>
      </div>
      <div class="info">
        <div class="item" v-for="(item, index) in dataList" :key="index">
          <div class="order">{{ item.Order }}</div>
          <div class="item-wrap">
            <div class="item-detail">
              <div :class="['status', item.status == 1 ? 'on-going' : 'completed']">
                {{ item.status == 1 ? '进行中' : '已完成' }}
              </div>
              <div class="delegation"></div>
              <div class="name">{{ item.AthleteName }}</div>
              <div class="horseName">
                <p>{{ item.CountryName }}</p>
                <p>{{ item.HorseName }}</p>
              </div>
              <div class="time">{{ item.Time }}</div>
              <div class="penalty">{{ formatToFixed(item.Punish) }}</div>
            </div>
            <img src="@/assets/img/scb/line-divide.png" alt="" height="5px" width="100%" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import useStore from '@/store'
import Config from '@/assets/js/config'
import { useMultiProcRequest } from '@/assets/js/useMultiProcRequest'
import { onBeforeMount } from 'vue'

const { formatToMinSecMs, results, fetchForProcs, fecthString } = useMultiProcRequest()

const gameInfo = ref({
  discipline: '马术',
  match: '',
  event: 'EVENTEAM',
  type: '实时成绩',
  startTime: '13:01:29',
  eventName: '',
})

let timer = null
const executions = ref(0)
const latestMsg = ref(null)
const interval = 50

const isRunning = ref(false)
const dataList = ref([])
// 存放消息的原始列表
const storedItems = ref([])

const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()
const params = ref({})
const procName = ref([])
const commonStore = useStore.useCommonStore()
let irmTimestamps = {}

onUnmounted(() => {
  clearInterval(timer)
})

onBeforeMount(() => {
  const lastMsg = commonStore.receivedActionMessages?.slice(-1)[0]
  if (lastMsg && lastMsg.tplCode == 'scb-cross-country-score') {
    latestMsg.value = lastMsg
    init()
  }
})

onMounted(async () => {
  params.value = route.query
  procName.value = Config.procNameList[route.name]
  await getData()
})

const getData = async () => {
  if (procName.value.length > 0) {
    await fetchForProcs(procName.value, {
      procName: procName.value[0],
      keyValues: params.value,
    })
  }
}

const getTimePenalty = (item) => {
  if (!latestMsg.value?.data?.penTime) return 0

  const currentTime = item.matchTime + executions.value
  if (currentTime <= latestMsg.value.data.penTime) return 0

  const timeout = currentTime - latestMsg.value.data.penTime
  const penalty =
    Math.floor(timeout / latestMsg.value.data.penSecond) * latestMsg.value.data.penScore
  return penalty
}

// 每次收到消息时，直接更新缓存
const updateStoredItems = (items) => {
  storedItems.value = [...items] // 覆盖更新
}

// 格式化一个 item，处理 15s IRM 过期逻辑
const formatDisplayItem = (item) => {
  if (!item) return null
  // const key = item.order
  // if (item.irm && !irmTimestamps[key]) {
  //   irmTimestamps[key] = Date.now()
  // }
  // const isIrmExpired = item.irm && irmTimestamps[key] && Date.now() - irmTimestamps[key] > 15000
  // if (isIrmExpired) return null

  return {
    Order: item.order,
    AthleteName: item.ath,
    CountryName: item.org,
    HorseName: item.horse,
    Time: item.irm
      ? ''
      : item.status == 3
      ? formatToMinSecMs(item.matchTime, true)
      : formatToMinSecMs(item.matchTime + executions.value),
    Punish: item.irm
      ? item.irm
      : item.status == 3
      ? Math.floor((item.timePenalty + item.jumpPenalty) * 100) / 100
      : Math.floor((getTimePenalty(item) + item.jumpPenalty) * 100) / 100,
    status: item.status || 1,
  }
}

// const getDataList = () => {
//   if (latestMsg.value?.data?.items?.length) {
//     const items = latestMsg.value.data.items
//     dataList.value = items
//       .map((item) => {
//         const key = item.order
//         if (item.irm) {
//           if (!irmTimestamps[key]) {
//             irmTimestamps[key] = Date.now()
//           }
//         }
//         const isIrmExpired =
//           item.irm && irmTimestamps[key] && Date.now() - irmTimestamps[key] > 15000
//         if (isIrmExpired) {
//           return null // 超过15秒就丢掉，不加入列表
//         }
//         return {
//           Order: item.order,
//           AthleteName: item.ath,
//           CountryName: item.org,
//           HorseName: item.horse,
//           Time: item.irm
//             ? item.irm
//             : item.status == 3 // 已完成，直接显示最终时间
//             ? formatToMinSecMs(item.matchTime, true)
//             : formatToMinSecMs(item.matchTime + executions.value), // 进行中：原时间 + 之前累计时间 + 新计时
//           Punish: item.irm
//             ? 1000
//             : item.status == 3
//             ? Math.floor((item.timePenalty + item.jumpPenalty) * 100) / 100
//             : Math.floor((getTimePenalty(item) + item.jumpPenalty) * 100) / 100,
//           status: item.status || 1,
//         }
//       })
//       .filter(Boolean) // 过滤掉 null
//   }
// }

// 生成展示列表
// 生成展示列表
const getDataList = () => {
  if (!latestMsg.value?.data?.items?.length) {
    dataList.value = []
    return
  }
  const list = latestMsg.value?.data?.items
  const results = list.map((it) => formatDisplayItem(it)).filter(Boolean)

  // 更新缓存（直接覆盖）
  // updateStoredItems(latestMsg.value.data.items)

  // const rawItems = latestMsg.value.data.items
  // const originalCount = rawItems.length

  // 格式化并过滤异常（IRM > 15s）
  // let list = rawItems.map((it) => formatDisplayItem(it)).filter(Boolean)

  // // 最多展示 4 条，目标数量是 min(4, 原始消息数)
  // const targetCount = Math.min(4, originalCount)

  // // 如果被过滤掉了，需要从缓存中补齐
  // if (list.length < targetCount) {
  //   const presentOrders = new Set(list.map((i) => i.Order))

  //   for (const cached of storedItems.value) {
  //     if (list.length >= targetCount) break
  //     if (presentOrders.has(cached.order)) continue

  //     const formatted = formatDisplayItem(cached)
  //     if (!formatted) continue

  //     list.push(formatted)
  //     presentOrders.add(cached.order)
  //   }
  // }

  // 最后再裁剪，确保最多 4 条
  dataList.value = results.slice(0, 4)
}

const formatToFixed = (num) => {
  if (typeof num !== 'number') return num
  if (num == 0) return 0
  if (num == 1000) return 1000
  const str = num.toString()
  const index = str.indexOf('.')
  if (index === -1) return str + '.0'
  return str.substring(0, index + 2).padEnd(index + 2, '0')
}

const stopTimer = () => {
  if (timer) {
    clearInterval(timer)
    timer = null
    isRunning.value = false
  }
}

let startTime = null
// 准备时间倒计时
const startTimer = () => {
  isRunning.value = true
  startTime = Date.now()
  executions.value = 0
  timer = setInterval(() => {
    const elapsed = Date.now() - startTime // 真实经过时间(ms)
    executions.value = Math.floor(elapsed) // 用真实时间换算执行次数
    getDataList()
  }, interval)
}

const init = () => {
  // 1. 暂停计时器
  stopTimer()

  // 2. 重新启动计时器（从 0 开始，但数据时间会加上 currentElapsedTime）
  executions.value = 0

  // 把最新消息的数据合并到缓存
  if (latestMsg.value?.data?.items?.length) {
    updateStoredItems(latestMsg.value.data.items)
  }

  // 3. 更新数据（getDataList 会使用 currentElapsedTime）
  getDataList()

  // 4. 重新启动计时器
  startTimer()
}

watchEffect(() => {
  if (results.value?.datasetList?.length) {
    gameInfo.value.event = results.value.datasetList[0][0]?.EventCode
    gameInfo.value.match = results.value.datasetList[0][0]?.MatchName
    gameInfo.value.eventName = results.value.datasetList[0][0]?.EventName
    // dataList.value = results.value.datasetList[1].slice(0, 4) || []
  }
})

watch(
  () => commonStore.receivedActionMessages,
  (newVal) => {
    if (newVal.length === 0) return

    const msg = newVal[newVal.length - 1]
    latestMsg.value = msg
    init()
  },
  { deep: true }
)

watch(
  () => route.query,
  (val) => {
    params.value = val
    getData()
  }
)
</script>

<style scoped lang="scss">
@import '@/assets/scss/event/crossCountryScore';
</style>
